<template>
  <div id="app">
    <h2>厨房有什么</h2>
    <p>由于经常会买各种食物，蔬菜、水果、面包等。许多东西放着放着可能自己都不知道了，有时候可能会导致一些食物坏掉。
      所以想创建一个项目用来实时记录厨房有什么食物。</p>
    <el-table :data="foods" stripe style="width: 100%">
      <el-table-column type="index" fit></el-table-column>
      <el-table-column prop="food_name" label="食物名称" sortable fit></el-table-column>
      <el-table-column label="食物类型" sortable fit>
        <template v-slot="{row}">
          {{ Number(row.food_type) === 1 ? '蔬菜' : '水果' }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="食物数量（个）" fit></el-table-column>
      <el-table-column prop="weight" label="食物质量（g）" fit></el-table-column>
      <el-table-column prop="create_date" label="创建时间" sortable fit></el-table-column>
      <el-table-column prop="save_time" label="保质期（天）" sortable fit></el-table-column>
      <el-table-column label="是否过期" fit><template v-slot="{row}">
          {{ row.is_expired === true ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" fit>
        <template #default>
          <el-button @click="deleteFood(index)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button v-on:click="addFood">添加食物</el-button>
  </div>
</template>

<script>
  const axios = require('axios')
  // 全局只有一个vue实例，前面已经声明了，这里只用export
  export default {
    // data必须是个函数，并且要返回

    // watch: {},
    // mounted: {},
    data() {
      return {
        tableHeader: ["号码", "食物名称", "食物类型", "食物数量（个）", "食物质量（g）", "创建时间", "保质期（天）", "是否过期", "操作"],
        foods: [],
        currency: "￥"
      }
    },
    methods: {
      getFoods() {
        const path = 'http://10.189.205.246:5000/getAll'
        axios
          .get(path)
          .then(res => {
            console.log(res)
            this.foods = res.data;
          })
          .catch(error => {
            console.error(error);
          });
      },
      deleteFood(index) {
        console.log("---删除" + index)
        console.log("---删除" + this.foods[index].food_name)
        const path = 'http://10.189.205.246:5000/deleteSingleFood'
        let post_data = {
          "food_name": this.foods[index].food_name
        }
        axios
          .post(path, post_data, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(() => {
            alert("删除" + this.foods[index].food_name + "成功")
            this.getFoods();
          })
          .catch(error => {
            console.log(error);
            this.getFoods();
          });
      },
      addFood() {
        this.$router.push("about")
      }
    },
    created() {
      this.getFoods();
    }
  }
</script>

<style>

</style>
